package auth

import (
	"context"
	"errors"
	"gitee.com/goddesszz/gocommon/myutil"
	"github.com/go-redis/redis/v8"
	"github.com/sirupsen/logrus"
	"monoblog/common"
	"monoblog/config"
	"strings"
	"time"
)

// SmsCodeCreateAndSend 生成smsCode并发送
func SmsCodeCreateAndSend(ctx context.Context, phone string) string {
	//生成随机验证码
	smscode := myutil.RandomNumberCode(6)

	_, err := config.GetRedisClient().Set(ctx, common.REDIS_VERIFY_CODE_PHONE_PREFIX+phone, smscode, 1*time.Minute).Result()
	if err != nil {
		logrus.Errorf("SmsCode save redis error: %v", err.Error())
		return ""
	}

	//发送smsCode给用户
	//模拟发送到手机
	return smscode
}

// SmsCodeVerify 验证码验证
func SmsCodeVerify(ctx context.Context, smscode string, phone string) bool {
	if strings.TrimSpace(smscode) == "" {
		logrus.Infof("[aid: %s] 参数 SmsCode is empty", ctx.Value("aid"))
		return false
	}

	storedSmscode, err := config.GetRedisClient().Get(ctx, common.REDIS_VERIFY_CODE_PHONE_PREFIX+phone).Result()
	if err != nil {
		// 1. 先判断是否为 "key 不存在" 错误（redis.Nil）
		if errors.Is(err, redis.Nil) {
			logrus.Infof("[aid: %s] SmsCode not found in redis (key does not exist or expired)", ctx.Value("aid")) // key不存在或过期
			return false
		}
		logrus.Errorf("[aid: %s] SmsCode get from redis error: %v", ctx.Value("aid"), err.Error())
		return false
	}

	//比较，忽略大小写
	correct := strings.EqualFold(smscode, storedSmscode)
	if correct {
		// 验证成功后，删除redis中的验证码
		config.GetRedisClient().Del(ctx, common.REDIS_VERIFY_CODE_PHONE_PREFIX+phone)
	}
	return correct
}
